<?php
/**
 * Created by PhpStorm.
 * User: liu
 * Date: 2018/6/14
 * Time: 22:54
 */

namespace app\common\traits;
use app\helper\Response;
use think\Model;


/**
 * 自己再次写一次封装  基础curd的操作 controller里面的操作
 * 嗯,去抄fastadmin的最好
 * Trait CURD
 * @package app\common\traits
 * @property Model $model
 */
trait CURD
{

    public function index(){
        if($this->request->isAjax()){
            list($where,$offset,$limit,$order)=$this->buildParams();
            $total=$this->model->where($where)
               ->count();
            $rows=$this->model->where($where)
                ->order($order)
                ->limit($offset,$limit)
                ->select();
            return Response::returnMsg(['count'=>$total,'rows'=>$rows]);
        }
        return $this->fetch();
    }
    public function add(){
        if($this->request->isAjax()){
            $param=$this->request->param();
            $r=$this->model->addHandler($param);
            if($r===false){
                return Response::returnMsg('',1,'添加失败,'.$this->model->getError());
            }
            return Response::returnMsg('',0,'添加成功');
        }
        return $this->fetch();

    }
    public function edit(){
        if($this->request->isAjax()){
            $param=input();
            $r=$this->model->editHandler($param);
            if($r===false){
                return Response::returnMsg('',1,'修改失败');
            }
            return Response::returnMsg('',0,'修改成功');
        }
        $id=input('id',0,'intval');
        $row=$this->model->find($id);
        if($row===false){
            return Response::returnMsg('',1,'修改非法对象');
        }
        $row=$this->model->where(['id'=>input('id',0,'intval')])
            ->find();
        if($row){
            $row=$row->toJson();
        }else{
            $row='{}';
        }
        return $this->fetch('',['row'=>$row]);
    }

    /*
     * 这是软删除
     */
    public function remove(){
        $id=input('id',0,'intval');
        $r=$this->model->remove($id);
        if($r===false){
            return Response::returnMsg('',1,'删除失败');
        }
        return Response::returnMsg('',0,'删除成功');

    }

    /**
     * 这是真删除
     */
    public function del(){
        $id=input('id',0,'intval');
        $r=$this->model->delete($id);
        if($r===false){
            return Response::returnMsg('',0,'彻底删除失败');
        }
        return Response::returnMsg('',0,'彻底删除成功');
    }
    protected function buildParams($search_fields=null,$relation_search=null){
        //这是查询字段
        $search_fields=is_null($search_fields)?$this->search_fields:$search_fields;
        //关联查询
        $relationSearch=is_null($relation_search)?$this->relation_search:$relation_search;



        $search=$this->request->get('search',[]);

        //查询过滤
        $filter=$this->request->get('filter','[]');
        //查询过滤的条件
        $op=$this->request->get('op','','trim');

        $order=$this->request->get('order','','trim');
//        $offset=$this->request->get('offset',0,'intval');
        $limit=$this->request->get('limit',10,'intval');
        $page=input('page',1,'intval');
        $offset=($page-1)*$limit;


        $filter=json_decode($filter,true);
        $op=json_decode($op,true);
        $order=json_decode($order,true);


        $where=[];

        $table_name='';

        if($relationSearch){
            if(!empty($this->model)){
                $table_name=$this->model->getQuery()->getTbale();
            }
            $tmp=[];
            foreach ($order as $k=>$v){
                $k=stripos($v,'.')===false?$table_name.'.'.$k:$k;
                $tmp[$k]=$v;
            }
            $order=$tmp;
        }

        if($search){
            $searcharr=is_array($search_fields)?$search_fields:explode(',',$search_fields);
            foreach ($searcharr as $k=>&$v){
                $v=stripos($v,'.')===false?$table_name.$v:$v;
            }
            unset($v);
            $where[]=[implode('|',$searcharr),'like',"%{$search}%"];
        }

        foreach ($filter as $k=>$v){
            $sym=isset($op[$k])?$op[$k]:'=';
            if(stripos($k,'.')===false)
            {
                $k=$table_name.$k;
            }
            $sym=strtoupper(isset($op[$k])?$op[$k]:$sym);
            switch ($sym){
                case '=':
                case '!=':
                    $where[]=[$k,$sym,(string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %..%':
                    $where[]=[$k,trim(str_replace('%..%','',$sym)),"%{$v}%"];
                    break;
                case '>=':
                case '>':
                case '<=':
                case '<':
                    $where[]=[$k,$sym,intval($v)];
                    break;
                case 'FINDIN':
                case 'FIND_IN_SET':
                    $where[]="FIND_IN_SET('{$v}',`{$k}`)";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[]=[$k,trim(str_replace('(...)','',$sym)),explode(',',$v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr=array_slice(explode(',',$v),0,2);
                    if(stripos($v,',')===false || !array_filter($arr)){
                        continue;
                    }
                    if($arr[0]===''){
                        $sym=$sym=='BETWEEN'?'<=':'>';
                        $arr=$arr[1];
                    }
                    elseif($arr[1]===''){
                        $sym=$sym=='BETWEEN'?'>=':'<';
                        $arr=$arr[0];
                    }
                    $where[]=[$k,$sym,$arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v=str_replace('-',',',$v);
                    $arr=array_slice(explode(',',$v),0,2);
                    if($arr[0]===''){
                        $sym=$sym=='RANGE'?'<=':'>';
                        $arr=$arr[1];
                    }elseif($arr[1]===''){
                        $sym=$sym=='RANGE'?'>=':'<';
                        $arr=$arr[0];
                    }
                    $where[]=[$k,$sym,$arr];
                    break;
                case 'NULL':
                case 'NOT NULL':
                case 'IS NULL':
                case 'IS NOT NULL':
                    $where[]=[$k,strtolower(str_replace('IS ','',$sym))];
                    break;
                default:
                    break;
            }
        }
        return [$where,$offset,$limit,$order];
    }
}